//
//  InfoViewController.m
//  心水宝典
//
//  Created by zr on 2018/8/29.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "InfoViewController.h"
#import "PGDatePickManager.h"
#import "UserInfoTableViewCell.h"
#import "UpdateNameViewController.h"

@interface InfoViewController ()<UITableViewDelegate,UITableViewDataSource,PGDatePickerDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray * showStringArray;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, assign)NSIndexPath * indexPAth;
@property (nonatomic, copy)NSString * str;
@end

@implementation InfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.showStringArray = @[@"我的头像",@"昵称",@"性别",@"生日"];
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}

- (void)setupNav{
    
    self.title = @"个人信息";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    //    backButton.frame = CGRectMake(0, 0, 20 * SCREENH6, 20 * SCREENH6);
    backButton.size = CGSizeMake(20 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
}


- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.rowHeight = 60 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.scrollEnabled = NO;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[UserInfoTableViewCell class] forCellReuseIdentifier:@"userInfoListCell"];
    
    [self.view addSubview:self.tableView];
    
}

//- (void)getPicture{
//
//    [self presentViewController:self.alertVC animated:YES completion:nil];
//}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{
    UserInfoTableViewCell * cell = [self.tableView cellForRowAtIndexPath:self.indexPAth];
    
    cell.iconImageView.image = image;
  
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.1);
    
    NSString * token = DEF_GET_OBJECT(@"token");
    
    NSDictionary * dic = @{@"files":frontImageData,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/files/Image/upload" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat  = @"yyyyMMddHHmmss";
        NSString *str  = [formatter stringFromDate:[NSDate date]];
        NSString *fileName  = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:frontImageData name:@"image" fileName:fileName mimeType:@"image/png"];
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"===%@",responseObject);
        
        int code = [responseObject[@"code"] intValue];
        
        if (code == 201){
            
            NSArray * arr = responseObject[@"data"];
            NSDictionary * dict = arr.firstObject;
            self.str = [NSString stringWithFormat:@"%@",dict[@"link"]];
            self.url = [NSURL URLWithString:self.str];
            
            [self.tableView reloadData];
            
            NSString * userid = DEF_GET_OBJECT(@"userid");
            NSString * str = [NSString stringWithFormat:@"/api/member/%@",userid];
    
            NSDictionary * dic = @{@"head":self.str,@"token":token};
            
            [[NetworkTool sharedTools] PUT:str parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                //        NSLog(@"responseData===%@",responseObject);
                
                NSString * status= [NSString stringWithFormat:@"%@",responseObject[@"code"]];
                
                if ([status isEqualToString:@"201"]) {
                    
                    
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseObject[@"msg"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              //                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
        }else{
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
    
}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UserInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userInfoListCell" forIndexPath:indexPath];
    
    cell.nameLabel.text = self.showStringArray[indexPath.row];
    
    if (indexPath.row == 0) {
        self.indexPAth = indexPath;
        
        cell.showLabel.hidden = YES;
        cell.iconImageView.hidden = NO;
        cell.url = self.url;
    }else{
        
        cell.showLabel.hidden = NO;
        cell.iconImageView.hidden = YES;
        
        if (indexPath.row == 1){

            cell.showLabel.text = self.name;
        }else if (indexPath.row == 2){

            cell.showLabel.text = [NSString stringWithFormat:@"%@",self.gender];
        }else if (indexPath.row == 3){

            cell.showLabel.text = [NSString stringWithFormat:@"%@",self.birthday];
        }
    }
    
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HIDDEN_TAB;
    
    UserInfoTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (indexPath.row == 1) {

        UpdateNameViewController * updateNameVC = [UpdateNameViewController new];

        updateNameVC.returnValueBlock = ^(NSString *strValue) {

            cell.nameLabel.text = strValue;
            
            [self.tableView reloadData];
        };

        [self.navigationController pushViewController:updateNameVC animated:YES];
    }else if (indexPath.row == 2){

        [self creatAlertController_sheet];
    }else if (indexPath.row == 3){

        [self presentDateController];
    }else if (indexPath.row == 0){
        
        [self presentViewController:self.alertVC animated:YES completion:nil];
    }
}



-(void)creatAlertController_sheet {
    
    NSString * userid = DEF_GET_OBJECT(@"userid");
    NSString * token = DEF_GET_OBJECT(@"token");
    NSString * str = [NSString stringWithFormat:@"/api/member/%@",userid];
    
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"请选择性别" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.gender = @"男";
        
        [self.tableView reloadData];
       
        NSDictionary * dict = @{@"sex":@"男",@"token":token};
        
        [[NetworkTool sharedTools] PUT:str parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //        NSLog(@"responseData===%@",responseObject);
            
            NSString * status= [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            
            if ([status isEqualToString:@"201"]) {
                
              
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"msg"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          //                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.gender = @"女";
        
        [self.tableView reloadData];
        
        NSDictionary * dict = @{@"sex":@"女",@"token":token};
        
        [[NetworkTool sharedTools] PUT:str parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //        NSLog(@"responseData===%@",responseObject);
            
            NSString * status= [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            
            if ([status isEqualToString:@"201"]) {
                
                
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"msg"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          //                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    //把action添加到actionSheet里
    [actionSheet addAction:action1];
    [actionSheet addAction:action2];
    [actionSheet addAction:action3];
    
    //相当于之前的[actionSheet show];
    [self presentViewController:actionSheet animated:YES completion:nil];
}


- (void)presentDateController{
    
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.isShadeBackgroud = true;
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.datePickerType = PGDatePickerType1;
    datePicker.isHiddenMiddleText = false;
    datePicker.datePickerMode = PGDatePickerModeDate;
    [self presentViewController:datePickManager animated:false completion:nil];
}


#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    
    self.birthday = [NSString stringWithFormat:@"%li-%02li-%02li",(long)dateComponents.year,dateComponents.month,dateComponents.day];
    
    [self.tableView reloadData];
    
    NSString * userid = DEF_GET_OBJECT(@"userid");
    NSString * token = DEF_GET_OBJECT(@"token");
    NSString * str = [NSString stringWithFormat:@"/api/member/%@",userid];
    
    NSDictionary * dict = @{@"birthday":self.birthday,@"token":token};
    
    [[NetworkTool sharedTools] PUT:str parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        NSLog(@"responseData===%@",responseObject);
        
        NSString * status= [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        
        if ([status isEqualToString:@"201"]) {

        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"msg"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      //                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)backToView {
   
    [self.navigationController popViewControllerAnimated:YES];
}


@end
